<template>
  <el-dialog :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
    <div>
      <el-form style="height:400px;overflow: auto;" ref="ruleFormRef" :model="ruleForm" :rules="rules"
        label-width="140px" class="demo-ruleForm" :disabled="dialogDatas?.type == 'check'">
        <!-- <el-form-item label="检测点ID" prop="id" v-if="dialogDatas.title=='新增' ? 1 :false">
          <el-input v-model="ruleForm.id" placeholder="请输入检测点ID" clearable maxlength="10" />
        </el-form-item> -->
        <el-form-item label="检测点名称" prop="pointName">
          <el-input v-model="ruleForm.pointName" placeholder="请输入检测点名称" clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="归属机构" prop="orgId" v-if="showOrg">
          <el-select :disabled="dialogDatas?.type === 'edit'" v-model="ruleForm.orgId" class="w-full"
            placeholder="请选择归属机构">
            <el-option v-for="(item) in orgIdDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="showOrg">
          <el-select v-model="ruleForm.status" class="w-full" placeholder="请选择状态">
            <el-option v-for="(item) in dialogDatas.enumListDatas" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区" prop="districtId" v-if="showOrg">
          <el-cascader v-model="diqu.array" @change="handleChange" :options="options" ref="cascaderAddr" clearable
            placeholder="请选择所在地区" />
        </el-form-item>
        <el-row>
          <el-col :span="21">
            <el-form-item label="详细地址" prop="detailedAddress">
              <el-input v-model="ruleForm.detailedAddress" placeholder="请输入详细地址" clearable maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="1"></el-col>
          <el-col :span="2">
            <el-button type="primary" @click="mapEvents">地图</el-button>
          </el-col>
        </el-row>
        <!-- <el-form-item label="经度" prop="longitude">
          <el-input v-model="ruleForm.longitude" placeholder="请输入经度" clearable maxlength="50" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="ruleForm.latitude" placeholder="请输入纬度" clearable maxlength="50" />
        </el-form-item> -->
        <el-form-item label="经纬度" prop="coordinates">
          <el-input v-model="ruleForm.coordinates" disabled placeholder="请输入经纬度" clearable maxlength="50" />
          <span style="color: #CCCCCC">注: 经纬度输入以英文逗号','连接 例(经度,纬度),且最终地图显示地址以经纬度为准</span>
        </el-form-item>

        <el-form-item label="客服电话" prop="customerTel">
          <el-input v-model="ruleForm.customerTel" placeholder="请输入客服电话" oninput="value=value.replace(/[^\d |\-]/g,'')"
            clearable  />
        </el-form-item>
        <el-form-item label="工作时间" prop="workDays">
          <el-col class="w-full celanerTime" @click="openWorkTime"
            :class="{ disableType: dialogDatas?.type == 'check' }">
            <span v-if="!ruleForm.workStartTime" style="color: #999;">请选择工作时间</span>
            <span v-else> {{ showWorkTime }}</span>
            <span class="caceder_icon"></span>
          </el-col>
        </el-form-item>
        <el-form-item label="每天最多预约人数" prop="workNum">
          <el-input v-model="ruleForm.workNum" placeholder="请输入每天最多预约人数" oninput="value=value.replace(/[^\d]/g,'')"
            clearable />
        </el-form-item>
        <!-- <el-form-item label="经纬度">
          <el-input v-model="ruleForm.coordinates" placeholder="请输入经纬度" clearable maxlength="10" />
        </el-form-item> -->
        <el-form-item label="负责人姓名">
          <el-input v-model="ruleForm.responsiblePersonName" placeholder="请输入负责人姓名" clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="负责人手机号">
          <el-input v-model="ruleForm.responsiblePersonPhone" @input="validatePhoneNumber" placeholder="请输入负责人手机号"
            clearable maxlength="11" />
          <!-- <div v-if="!isValidPhone" style="color: red;">手机号码格式不正确</div> -->
        </el-form-item>
      </el-form>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
    <el-dialog class="workTime" title="工作时间设置" :width="600" :model-value="calendarVisible" @close="closedCalendar">
      <el-checkbox-group v-model="checkList" style="margin-top: 24px;">
        <el-checkbox v-for="(item, index) in weekList" :key="index" :label="item" :value="index + 1" />
      </el-checkbox-group>
      <div style="margin-top: 24px;margin-bottom: 24px;">
        工作时间：
        <el-time-select v-model="startTime" style="width: 150px" :max-time="endTime" class="mr-4" placeholder="开始时间"
          start="00:00" step="00:15" end="24:00" />
        <el-time-select v-model="endTime" style="width: 150px" :min-time="startTime" placeholder="结束时间" start="00:00"
          step="00:15" end="24:00" />
      </div>
      <template #footer>
        <span class="dialog-footer" style="display: block;text-align: center;">
          <el-button @click="cancelCalendar">取消</el-button>
          <el-button type="primary" @click="entryCalendar">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <map-dialog ref="mapDialogRef" @mapInfo="mapInfo"></map-dialog>
  </el-dialog>
</template>
<script lang="ts" setup>
import { watch, ref, reactive, onBeforeMount, toRefs, computed } from 'vue';
import { getEnumListRequest, orgOptionsRequest, getCheckPointsOptionsRequest } from '@/api/common';
import {
  addCheckPointsRequest,
  editCheckPointsRequest,
  getCheckPointsDetailRequest,
} from '@/api/checkPoint';
import type { FormInstance, FormRules } from 'element-plus';
import regionData from '@/assets/json/regionData.json';
import { ru } from 'element-plus/es/locale';
import mapDialog from '../mapDialog.vue'
const options = ref(regionData);
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible', 'handleFormValue']);


const showWorkTime = computed(() => {
  const day = weekList.filter((item, index) => ruleForm.workDays.includes(index + 1))
  return day.join('，') + ' ' + ruleForm.workStartTime + '-' + ruleForm.workEndTime
}
)
const visible = ref(false);
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const checkList = ref([] as any[])
const startTime = ref('')
const endTime = ref('')
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  pointName: null,
  orgId: '',
  customerTel: '',
  workNum: '',
  workDays: '',
  workStartTime: '',
  workEndTime: '',
  status: '',
  provinceId: '',
  cityId: '',
  districtId: '',
  detailedAddress: '',
  coordinates: '',
  responsiblePersonName: '',
  responsiblePersonPhone: '',
  // longitude: '',
  // latitude: '',
})
// let chanFormValue = reactive({});
watch(dialogDatas, () => {
  // console.log('11111')
  // dialogDatas.value.datas.forEach((d: { value: any[]; type: string; eName: string | number | any[] }) => {
  //   if (d.value||d.value===0) {
  //     if (d.type === 'cascader') {
  //       d.keys.forEach((item: string | number, i: number) => {
  //         chanFormValue[item] = d.value[i];
  //       });
  //       return;
  //     }
  //     chanFormValue[d.eName] = d.value;
  //     console.log(d.value,)
  //   }else{
  //     delete  chanFormValue[d.eName]
  //   }
  // });
  // emit('handleFormValue', chanFormValue);
});
const weekList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
// 校验
const rules = reactive<FormRules>({
  // id: [{ required: true, message: '请输入检测点ID', trigger: 'change' },],
  customerTel: [{ required: true, message: '请输入客服电话', trigger: 'change' }],
  workNum: [{ required: true, message: '请输入每天最多预约人数', trigger: 'blur' },
  {
    validator(rule, value, callback) {
      if (Number.isInteger(Number(value)) && Number(value) >= 10 && Number(value) <= 2000) {
        callback()
      } else {
        callback(new Error('请输入不小于10 不大于2000的数字'))
      }
    },
    trigger: 'blur'
  }],
  workDays: [{ required: true, message: '请输入工作时间', trigger: 'change' }],
  // longitude: [{ required: true, message: '请输入经度', trigger: 'change' }],
  // latitude: [{ required: true, message: '请输入纬度', trigger: 'change' }],
  coordinates: [{ required: true, message: '请输入经纬度', trigger: 'change' }],
  pointName: [{ required: true, message: '请输入检测点名称', trigger: 'change' }],
  orgId: [{ required: true, message: '选择归属组织', trigger: 'change' }],
  status: [{ required: true, message: '选择状态', trigger: 'change' }],
  districtId: [{ required: true, message: '选择所在地区', trigger: 'change' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
  // { validator: checkAge, trigger: 'blur' }
})
let diqu = reactive({ array: [] });
const value = ref([])
const handleChange = (value) => {
  ruleForm.provinceId = value[0]
  ruleForm.cityId = value[1]
  ruleForm.districtId = value[2]
  console.log(value, "sdfsfasdf")
}

const isValidPhone = computed(() => /^1[3-9]\d{9}$/.test(ruleForm.responsiblePersonPhone));

function validatePhoneNumber(event) {
  // 限制只能输入数字
  ruleForm.responsiblePersonPhone = event.replace(/\D/g, '');
}
//提交
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // ruleForm.coordinates = `${ruleForm.longitude},${ruleForm.latitude}`
      let Url = dialogDatas.value.type == 'add' ? addCheckPointsRequest : editCheckPointsRequest;
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')
    } else {
      console.log('保存失败', fields)
    }
  })
}
const mapDialogRef = ref(null)
const mapEvents = () => {
   // 如果输入的又经纬度就按照输入的去展示地图 没有则显示默认公司定位
  if(ruleForm.coordinates) {
    const [long, lat] = ruleForm.coordinates.split(',');
    let obj = {
      detailedAddress: ruleForm.detailedAddress,
      longitude: long,
      latitude: lat
    }
    mapDialogRef.value.show(obj)
  } else {
    let obj = {
      detailedAddress: ruleForm.detailedAddress,
      longitude: 120.168663,
      latitude: 30.187154
    }
    mapDialogRef.value.show(obj)
  } 

}
// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}
// 归属机构下拉
let orgIdDatas = reactive([
  { id: null, name: null }])
let showOrg = ref(true)
const getOrgOptionsDatas = async () => {
  showOrg.value = false
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
  console.log(orgIdDatas, "orgIdDatas")
  showOrg.value = true
};
let enumListDatas = reactive([{ id: null, name: null }]); //设备状态下拉数据
/* 获取设备状态数据（筛选） */
const getEnumListDatas = async () => {
  showOrg.value = false
  const data: any = await getEnumListRequest({ enumName: 'CheckPointsStatusEnum' });
  enumListDatas = data.data;
  // showOrg.value = true
};

// 获取详情
const getDetailsFun = async () => {
  const data: any = await getCheckPointsDetailRequest({ checkPointsId: dialogDatas.value.datas.id });
  let res = data.data
  ruleForm.id = res.id
  ruleForm.pointName = res.pointName
  ruleForm.orgId = res.orgId
  ruleForm.status = res.status
  diqu.array = [res.provinceId.toString(), res.cityId.toString(), res.districtId.toString()]
  ruleForm.detailedAddress = res.detailedAddress
  ruleForm.coordinates = res.coordinates
  ruleForm.responsiblePersonName = res.responsiblePersonName
  ruleForm.responsiblePersonPhone = res.responsiblePersonPhone
  ruleForm.provinceId = res.provinceId
  ruleForm.cityId = res.cityId
  ruleForm.districtId = res.districtId
  ruleForm.workNum = res.workNum
  ruleForm.workDays = res.workDays
  ruleForm.workStartTime = res.workStartTime
  ruleForm.workEndTime = res.workEndTime
  ruleForm.customerTel = res.customerTel
  // if(res.coordinates) {
  //   const [long, lat] = res.coordinates.split(',');
  //   ruleForm.longitude = long;
  //   ruleForm.latitude = lat;
  // } 
}
const calendarVisible = ref(false)

const openWorkTime = () => {
  if (dialogDatas.value?.type == 'check') {
    return
  }
  checkList.value = ruleForm.workDays || []
  startTime.value = ruleForm.workStartTime
  endTime.value = ruleForm.workEndTime
  console.log('打开选择时间弹框');
  calendarVisible.value = true
}
const closedCalendar = () => {
  calendarVisible.value = false
}

const cancelCalendar = () => {
  closedCalendar()
}
const mapInfo = (e:any) => {
  // ruleForm.longitude = e.longitude
  // ruleForm.latitude = e.latitude
  ruleForm.detailedAddress = e.address
  // ruleForm.coordinates = e.longitude + e.latitude
  ruleForm.coordinates = `${e.longitude},${e.latitude}`
}
const entryCalendar = () => {
  console.log(checkList.value, startTime.value, endTime.value);
  if (!checkList.value.length) {
    ElMessage.error('请选择工作日')
    return
  }
  if (!startTime.value) {
    ElMessage.error('请选择工作开始时间')
    return
  }
  if (!endTime.value) {
    ElMessage.error('请选择工作结束时间')
    return
  }
  ruleForm.workDays = checkList.value
  console.log(checkList.value);
  
  ruleForm.workStartTime = startTime.value
  ruleForm.workEndTime = endTime.value
  console.log(ruleForm);
  ruleFormRef.value?.clearValidate()
  closedCalendar()
}
onBeforeMount(async () => {
  getOrgOptionsDatas()
  getEnumListDatas()
  console.log(dialogDatas.value.type);

  if (dialogDatas.value.type == 'add') {
    // getMenuList()
  } else {
    getDetailsFun()
  }
})
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  text-align: center;
}

.celanerTime {
  height: 32px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 3px;
  text-indent: 10px
}

.caceder_icon {
  position: absolute;
  right: 10px;
  top: 5px;
  width: 18px;
  height: 18px;
  background: url('@/assets/image/cacel_icon.png') center center no-repeat;
  background-size: cover;
}

.disableType {
  color: #a8abb2;
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>
